package com.thti.mecool.client.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.model.biz.TaskStepBizImpl;
import com.thti.mecool.client.model.po.TaskManage;
import com.thti.mecool.client.util.FileUtil;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.Toolbar;

public class ChoiceFileActivity extends BaseActivity {
	private ArrayList<File> files;
	private String path;
	private File root;
	private File save;
	private SharedPreferences load;
	private ByteArrayOutputStream out;
	private TaskManage taskManage;
	private BaseAdapter ba = new BaseAdapter() {
		class ViewHolder {
			TextView text;
			ImageView img;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(ChoiceFileActivity.this)
						.inflate(R.layout.choice_file_item, null);
				holder.text = (TextView) convertView
						.findViewById(R.id.mecool_choice_file_item_text);
				holder.img = (ImageView) convertView
						.findViewById(R.id.mecool_choice_file_item_img);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (files.get(position).isDirectory())
				holder.img.setImageResource(R.drawable.folder);
			else
				holder.img.setImageResource(R.drawable.file_icon_picture);
			holder.text.setText(files.get(position).getName());

			return convertView;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return files.get(arg0);
		}

		@Override
		public int getCount() {
			return files.size();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		noTitle();
		setContentView(R.layout.mecool_file_choice);
		Cache.add(this);
		load = getSharedPreferences("LocationService", 0);
		ListView lv = (ListView) findViewById(R.id.mecool_file_choice_list);
		files = new ArrayList<File>();
		taskManage = new TaskManage();
		// sdcard卡根目录
		root = new File("..");
		String planId = getIntent().getStringExtra("planId");
		String projectId = getIntent().getStringExtra("projectId");
		String taskId = getIntent().getStringExtra("taskId");
		String stepId = getIntent().getStringExtra("stepId");
		taskManage.setPlanId(planId);
		taskManage.setProjectId(projectId);
		taskManage.setTaskId(taskId);
		taskManage.setStepId(stepId);
		Toolbar toolbar = new Toolbar(this);
		Toolbar.left_btn.setOnClickListener(onClickListener);
		Toolbar.hideRightButton();
		path = root.getAbsolutePath();
		files.addAll(FileUtil.execPath(path));
		lv.setAdapter(ba);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (files.get(arg2).isDirectory()) {
					path = files.get(arg2).getAbsolutePath();
					files.clear();
					files.addAll(FileUtil.execPath(path));
					ba.notifyDataSetChanged();
				} else {
		save = files.get(arg2);
					new AlertDialog.Builder(ChoiceFileActivity.this)
							.setTitle("提示")
							.setMessage(
									"确认选择 \"" + files.get(arg2).getName()
											+ "\" 为上传附件吗？\n文件大小为 : "+save.length()/1024+"k")
							.setNegativeButton("否", dialogClickListener)
							.setPositiveButton("是", dialogClickListener)
							.create().show();
				}
			}
		});
	}

	OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_toolbar_leftbtn:
				finish();
				break;
			default:
				break;
			}
		}
	};

	private void complete() {
		try {
			FileInputStream fis = new FileInputStream(save);
			out = new ByteArrayOutputStream(4096);
			int len;
			byte[] buf = new byte[1024];
			while ((len = fis.read(buf)) != -1) {
				out.write(buf, 0, len);
			}
			taskManage.setImages(out.toByteArray());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		taskManage.setData(save.getName());
		taskManage.setLatitude(load.getString("Latitude", null));
		taskManage.setLongitude(load.getString("Longitude", null));
		TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
		// 存入数据库
		taskStepBizImpl.updateData(taskManage);
	}

	public void isFinish(int finish) {
		TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(
				ChoiceFileActivity.this);
		List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
		Map<String, Object[]> map = new HashMap<String, Object[]>();
		String[] ids = new String[] { String.valueOf(finish),
				taskManage.getPlanId(), taskManage.getProjectId(),
				taskManage.getStepId(), taskManage.getTaskId() };
		map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
		list.add(map);
		taskStepBizImpl.updateStep(list);
	}

	private android.content.DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			System.out.println("save.length()   :   "+save.length());
			switch (which) {
			case -1:
				if(save.length()>800*1024){
					dialog.dismiss();
					Util.sendToast(ChoiceFileActivity.this, "附件大小不能超过800k");
				}
				else{
				complete();
				isFinish(1);
				finish();
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == 4) {
			if (path.equals(root.getAbsolutePath())) {
				finish();
			} else {
				path = new File(path).getParent();
				files.clear();
				files.addAll(FileUtil.execPath(path));
				ba.notifyDataSetChanged();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
